extends CanvasLayer

# 引用技能数据库
const SkillDatabase = preload("res://scripts/skills/database/skill_database.gd")
# 引用玩家属性类
const PlayerStats = preload("res://scripts/player/player_stats.gd")

var skill_data = SkillDatabase.skill_data
var stats: Variant = null  # 使用Variant类型以支持不同类型的值
var selected_skill = null

# 技能树布局配置
const GRID_SIZE = Vector2(120, 150)  # 减小网格大小
const GRID_MARGIN = Vector2(30, 40)  # 调整边距
const GRID_COLUMNS = 5  # 恢复为每行5个技能
const SKILL_CATEGORIES = {
	"basic": {"name": "基础技能", "row": 0, "color": Color(0.2, 0.6, 0.8)},
	"advanced": {"name": "进阶技能", "row": 1, "color": Color(0.8, 0.2, 0.2)},
	"master": {"name": "大师技能", "row": 2, "color": Color(0.2, 0.8, 0.2)}
}

# 添加一个变量来控制调试输出频率
var debug_timer = 0.0
var debug_interval = 2.0  # 每2秒输出一次调试信息

func _ready():
	print("技能树初始化开始")
	
	# 检查必要的节点是否存在
	if not $Control:
		push_error("错误：找不到Control节点！")
		return
		
	if not $Control/Background:
		push_error("错误：找不到Background节点！")
		return
		
	if not $Control/Background/SkillContainer:
		push_error("错误：找不到SkillContainer节点！")
		return
		
	if not $Control/Background/SkillContainer/BasicSkills:
		push_error("错误：找不到BasicSkills节点！")
		return
		
	if not $Control/Background/SkillContainer/AdvancedSkills:
		push_error("错误：找不到AdvancedSkills节点！")
		return
		
	if not $Control/Background/SkillContainer/MasterSkills:
		push_error("错误：找不到MasterSkills节点！")
		return
	
	# 连接关闭按钮信号
	if $Control/Background/CloseButton:
		if $Control/Background/CloseButton.pressed.is_connected(_on_close_button_pressed):
			$Control/Background/CloseButton.pressed.disconnect(_on_close_button_pressed)
		$Control/Background/CloseButton.pressed.connect(_on_close_button_pressed)
		print("关闭按钮信号已连接")
	else:
		push_error("错误：找不到关闭按钮！")
	
	# 获取玩家数据
	var player = get_tree().get_first_node_in_group("player")
	if player:
		print("找到玩家节点: ", player.name)
		if player.has_method("get_stats"):
			stats = player.get_stats()
			print("成功获取玩家数据")
		else:
			stats = player.stats
			print("通过直接访问获取玩家数据")
	else:
		push_error("错误：找不到玩家节点！")
		stats = PlayerStats.new()
		stats.level = 5
		print("创建临时测试数据")
	
	# 检查并创建连接线节点
	if not $Control/Background/SkillContainer/Connections:
		var connections = Line2D.new()
		connections.name = "Connections"
		connections.width = 2.0
		connections.default_color = Color(0.8, 0.3, 0.9, 0.8)
		connections.antialiased = true
		$Control/Background/SkillContainer.add_child(connections)
		print("创建了缺失的Connections节点")
	
	# 等待一帧以确保所有节点都准备好
	await get_tree().process_frame
	
	# 创建技能节点
	create_nodes()
	
	# 绘制连接线
	draw_connections()
	
	# 初始化描述面板
	if $Control/Background/DescriptionPanel:
		$Control/Background/DescriptionPanel.visible = false
	else:
		push_error("错误：找不到描述面板！")
	
	print("技能树初始化完成")

func _on_close_button_pressed():
	print("关闭按钮被点击")
	
	# 查找玩家节点
	var player = get_tree().get_first_node_in_group("player")
	if player:
		print("找到玩家节点: ", player.name)
		
		if player.has_method("close_skill_tree"):
			print("玩家节点有close_skill_tree方法，调用它")
			player.close_skill_tree()
			print("通过玩家节点关闭技能树")
		else:
			print("玩家节点没有close_skill_tree方法，尝试直接销毁")
			# 列出玩家节点的所有方法
			print("玩家节点可用方法: ", player.get_method_list())
			queue_free()
	else:
		print("找不到玩家节点，尝试直接销毁")
		queue_free()
	
	# 无论如何，确保自己被销毁
	call_deferred("queue_free")
	print("技能树将被销毁")

# 创建分类标签
func create_category_labels():
	# 清除之前的标签
	for child in $Control/Background/SkillContainer/CategoryLabels.get_children():
		child.queue_free()
	
	# 为每个类别创建标签
	for category_id in SKILL_CATEGORIES:
		var category = SKILL_CATEGORIES[category_id]
		
		# 创建标签
		var label = Label.new()
		label.name = "Category_" + category_id
		label.text = category.name
		label.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
		label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
		
		# 设置标签位置
		var pos_y = category.row * (GRID_SIZE.y + GRID_MARGIN.y)
		label.position = Vector2(20, pos_y - 30)  # 将标签放在技能上方
		label.size = Vector2(200, 30)
		
		# 设置标签样式
		label.add_theme_font_size_override("font_size", 20)
		label.add_theme_color_override("font_color", category.color)
		
		# 添加到容器
		$Control/Background/SkillContainer/CategoryLabels.add_child(label)
		
	print("类别标签创建完成")

# 查找技能节点
func find_skill_node(skill_id):
	var grids = [
		$Control/Background/SkillContainer/BasicSkills/GridContainer,
		$Control/Background/SkillContainer/AdvancedSkills/GridContainer,
		$Control/Background/SkillContainer/MasterSkills/GridContainer
	]
	
	for grid in grids:
		for node in grid.get_children():
			if node.has_meta("skill_id") and node.get_meta("skill_id") == skill_id:
				return node
	return null

func create_nodes():
	# 检查必要的节点是否存在
	var basic_grid = $Control/Background/SkillContainer/BasicSkills/GridContainer
	var advanced_grid = $Control/Background/SkillContainer/AdvancedSkills/GridContainer
	var master_grid = $Control/Background/SkillContainer/MasterSkills/GridContainer
	
	if not basic_grid or not advanced_grid or not master_grid:
		push_error("错误：找不到必要的网格容器节点！")
		print("基础技能网格：", basic_grid)
		print("进阶技能网格：", advanced_grid)
		print("大师技能网格：", master_grid)
		return
	
	# 清除之前的节点
	for grid in [basic_grid, advanced_grid, master_grid]:
		for child in grid.get_children():
			child.queue_free()
	
	# 按类别组织技能
	var skills_by_category = {
		"basic": [],
		"advanced": [],
		"master": []
	}
	
	# 将技能分类
	for skill_id in skill_data:
		var category = "basic"  # 默认类别
		if skill_data[skill_id].has("category"):
			category = skill_data[skill_id].category
		
		if skills_by_category.has(category):
			skills_by_category[category].append(skill_id)
	
	# 创建技能节点
	for category in skills_by_category:
		var skills = skills_by_category[category]
		var grid = null
		
		# 获取对应的网格容器
		match category:
			"basic":
				grid = basic_grid
			"advanced":
				grid = advanced_grid
			"master":
				grid = master_grid
		
		if not grid:
			push_error("错误：找不到类别 " + category + " 的网格容器！")
			continue
		
		# 在网格中创建技能节点
		for skill_id in skills:
			var node = preload("res://scenes/skill_node.tscn").instantiate()
			if not node:
				push_error("错误：无法实例化技能节点！")
				continue
				
			node.custom_minimum_size = Vector2(100, 120)
			
			# 设置节点名称
			var name_label = node.get_node_or_null("NameLabel")
			if name_label:
				name_label.text = skill_data[skill_id].name
				name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
				name_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
				name_label.position = Vector2(-45, 5)  # 将X轴位置改为0，使其更靠左
				name_label.size = Vector2(90, 20)
				name_label.add_theme_font_size_override("font_size", 12)
				name_label.clip_text = true  # 添加文本裁剪
			
			# 调整等级文本位置和大小
			var cost_label = node.get_node_or_null("CostLabel")
			if cost_label:
				cost_label.text = "需求: " + str(skill_data[skill_id].cost) + "级"
				cost_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
				cost_label.vertical_alignment = VERTICAL_ALIGNMENT_TOP
				cost_label.position = Vector2(25, 0)  # X轴从15改为20，向右移动
				cost_label.size = Vector2(90, 20)
				cost_label.add_theme_font_size_override("font_size", 12)
			
			# 确保Icon节点存在并调整大小和位置
			if node.has_node("Icon") and skill_data[skill_id].has("icon"):
				var icon = node.get_node("Icon")
				icon.texture = load(skill_data[skill_id].icon)
				icon.custom_minimum_size = Vector2(60, 60)
				icon.position = Vector2(-30, 35)  # X轴位置改为15，使图标更靠左
				icon.size = Vector2(60, 60)
				icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
			
			node.set_meta("skill_id", skill_id)
			grid.add_child(node)
			
			# 添加点击事件以显示技能描述
			var button = Button.new()
			button.name = "DescriptionButton"
			button.flat = true
			button.set_anchors_preset(Control.PRESET_FULL_RECT)
			button.mouse_filter = Control.MOUSE_FILTER_PASS
			button.pressed.connect(func(): _on_skill_info_requested(skill_id))
			node.add_child(button)
			
			# 调整学习按钮的位置和大小
			var learnedBtn = TextureButton.new()
			learnedBtn.name = "LearnButton"
			learnedBtn.set_position(Vector2(25, 95))
			learnedBtn.set_size(Vector2(50, 20))
			learnedBtn.z_index = 10
			learnedBtn.mouse_filter = Control.MOUSE_FILTER_STOP
			learnedBtn.focus_mode = Control.FOCUS_ALL
			
			# 创建按钮背景和文本
			var button_bg = ColorRect.new()
			button_bg.name = "Background"
			button_bg.set_anchors_preset(Control.PRESET_FULL_RECT)
			button_bg.color = Color(0.2, 0.6, 0.9, 0.8)
			learnedBtn.add_child(button_bg)
			
			var button_text = Label.new()
			button_text.name = "Text"
			button_text.text = "学习"
			button_text.set_anchors_preset(Control.PRESET_FULL_RECT)
			button_text.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
			button_text.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
			button_text.add_theme_color_override("font_color", Color(1, 1, 1))
			button_text.add_theme_font_size_override("font_size", 14)
			learnedBtn.add_child(button_text)
			
			# 连接按钮信号
			learnedBtn.pressed.connect(func():
				print("学习按钮被点击: ", skill_id)
				_on_skill_selected(skill_id)
			)
			
			# 添加鼠标悬停效果
			learnedBtn.mouse_entered.connect(func(): 
				button_bg.color = Color(0.3, 0.7, 1.0, 0.9)
			)
			learnedBtn.mouse_exited.connect(func(): 
				button_bg.color = Color(0.2, 0.6, 0.9, 0.8)
			)
			
			node.add_child(learnedBtn)
			
			# 设置节点背景颜色
			if node.has_node("Background"):
				var bg_color = Color(0.2, 0.6, 0.8) if category == "basic" else \
							Color(0.8, 0.2, 0.2) if category == "advanced" else \
							Color(0.2, 0.8, 0.2)  # 大师技能使用绿色
				node.get_node("Background").color = bg_color.darkened(0.5)
			
			update_node_state(node, skill_id)
			print("节点"+skill_data[skill_id].name+"创建完毕")
	
	print("所有技能节点创建完成")

func update_node_state(node, skill_id):
	if not is_instance_valid(node):
		push_error("错误：技能节点无效")
		return
		
	if not skill_data.has(skill_id):
		push_error("错误：无效的技能ID - " + str(skill_id))
		return
	
	# 检查stats是否有效
	var learned = false
	var can_afford = false
	var player_level = 0
	
	if is_instance_valid(stats):
		if stats is Object:
			if stats.has_method("has_skill"):
				learned = stats.has_skill(skill_id)
			
			if stats.get("level") != null:
				player_level = stats.level
				can_afford = player_level >= skill_data[skill_id].cost
		elif typeof(stats) == TYPE_DICTIONARY:
			if stats.has("skills"):
				if typeof(stats.skills) == TYPE_ARRAY:
					learned = skill_id in stats.skills
				elif typeof(stats.skills) == TYPE_DICTIONARY:
					learned = stats.skills.has(skill_id)
			
			if stats.has("level"):
				player_level = stats.level
				can_afford = player_level >= skill_data[skill_id].cost
	
	# 更新节点外观
	var skill = skill_data[skill_id]
	
	# 获取节点的各个组件
	var icon = node.get_node_or_null("Icon")
	var name_label = node.get_node_or_null("NameLabel")
	var desc_label = node.get_node_or_null("DescLabel")
	var cost_label = node.get_node_or_null("CostLabel")
	var learn_button = node.get_node_or_null("LearnButton")
	var locked_overlay = node.get_node_or_null("LockedOverlay")
	
	# 设置技能信息
	if name_label:
		name_label.text = skill.name
	
	if desc_label:
		desc_label.text = skill.description
	
	if cost_label:
		cost_label.text = "需求: " + str(skill.cost) + "级"
	
	# 更新节点状态
	if learned:
		# 已学习的技能
		if locked_overlay:
			locked_overlay.visible = false
		
		# 更新节点背景为绿色
		var bg = node.get_node_or_null("Background")
		if bg:
			bg.color = Color(0.2, 0.8, 0.2, 0.7)  # 绿色背景
		
		# 更新技能名称，添加勾选标记
		if name_label and not name_label.text.ends_with(" ✓"):
			name_label.text = skill.name + " ✓"
		
		# 禁用学习按钮
		if learn_button:
			learn_button.disabled = true
			
			# 更新按钮文本
			var button_text = learn_button.get_node_or_null("Text")
			if button_text:
				button_text.text = "已学习"
			
			# 更新按钮背景
			var button_bg = learn_button.get_node_or_null("Background")
			if button_bg:
				button_bg.color = Color(0.2, 0.8, 0.2, 0.8)  # 绿色背景
	else:
		# 未学习的技能
		if can_afford:
			# 可以学习的技能
			if locked_overlay:
				locked_overlay.visible = false
			
			# 更新节点背景为蓝色
			var bg = node.get_node_or_null("Background")
			if bg:
				bg.color = Color(0.2, 0.6, 0.9, 0.7)  # 蓝色背景
			
			# 启用学习按钮
			if learn_button:
				learn_button.disabled = false
				learn_button.visible = true
		else:
			# 无法学习的技能
			if locked_overlay:
				locked_overlay.visible = true
			
			# 更新节点背景为灰色
			var bg = node.get_node_or_null("Background")
			if bg:
				bg.color = Color(0.5, 0.5, 0.5, 0.7)  # 灰色背景
			
			# 禁用学习按钮
			if learn_button:
				learn_button.disabled = true
				learn_button.visible = true
	
	print("更新节点状态：", skill.name, " - 已学习：", learned, "，可学习：", can_afford)

func _on_skill_selected(skill_id):
	print("\n===== 开始学习技能 =====")
	print("技能ID: ", skill_id)
	
	# 检查技能ID是否有效
	if not skill_data.has(skill_id):
		push_error("错误：无效的技能ID - " + str(skill_id))
		return false
	
	print("技能名称: ", skill_data[skill_id].name)
	print("技能所需等级: ", skill_data[skill_id].cost)
	
	# 检查stats是否有效
	if not is_instance_valid(stats):
		push_error("错误：stats 未初始化，无法学习技能！")
		return false
	
	# 获取玩家当前等级
	var player_level = 0
	if stats is Object:
		if stats.has_method("get_level"):
			player_level = stats.get_level()
		elif stats.get("level") != null:
			player_level = stats.level
	elif typeof(stats) == TYPE_DICTIONARY and stats.has("level"):
		player_level = stats.level
	
	print("玩家当前等级：", player_level)
	
	# 检查是否已学习该技能
	var already_learned = false
	if stats is Object:
		if stats.has_method("has_skill"):
			already_learned = stats.has_skill(skill_id)
		elif stats.get("skills") != null:
			if typeof(stats.skills) == TYPE_ARRAY:
				already_learned = skill_id in stats.skills
			elif typeof(stats.skills) == TYPE_DICTIONARY:
				already_learned = stats.skills.has(skill_id)
	elif typeof(stats) == TYPE_DICTIONARY and stats.has("skills"):
		if typeof(stats.skills) == TYPE_ARRAY:
			already_learned = skill_id in stats.skills
		elif typeof(stats.skills) == TYPE_DICTIONARY:
			already_learned = stats.skills.has(skill_id)
	
	if already_learned:
		print("技能已学习，无需重复学习")
		return false
	
	# 检查玩家等级是否足够
	if player_level < skill_data[skill_id].cost:
		print("等级不足，无法学习技能")
		return false
	
	print("玩家等级足够，开始学习技能")
	
	# 尝试学习技能
	var success = false
	if stats is Object:
		if stats.has_method("learn_skill"):
			success = stats.learn_skill(skill_id)
		else:
			# 手动添加技能
			if stats.get("skills") != null:
				if typeof(stats.skills) == TYPE_ARRAY:
					stats.skills.append(skill_id)
					success = true
				elif typeof(stats.skills) == TYPE_DICTIONARY:
					stats.skills[skill_id] = true
					success = true
	elif typeof(stats) == TYPE_DICTIONARY:
		if not stats.has("skills"):
			stats.skills = {}
		
		if typeof(stats.skills) == TYPE_DICTIONARY:
			stats.skills[skill_id] = true
			success = true
		elif typeof(stats.skills) == TYPE_ARRAY:
			stats.skills.append(skill_id)
			success = true
	
	if success:
		print("成功学习技能：", skill_data[skill_id].name)
		
		# 更新节点状态
		var skill_node = find_skill_node(skill_id)
		if skill_node:
			update_node_state(skill_node, skill_id)
			
			# 添加学习成功的视觉反馈
			var tween = create_tween()
			tween.tween_property(skill_node, "modulate", Color(1.5, 1.5, 1.5), 0.2)
			tween.tween_property(skill_node, "modulate", Color(1, 1, 1), 0.3)
		
		# 更新所有节点状态
		update_all_nodes()
		
		# 重新绘制连接线
		draw_connections()
		
		print("===== 技能学习完成 =====\n")
		return true
	else:
		print("学习技能失败：", skill_data[skill_id].name)
		print("===== 技能学习失败 =====\n")
		return false

func update_all_nodes():
	var grids = [
		$Control/Background/SkillContainer/BasicSkills/GridContainer,
		$Control/Background/SkillContainer/AdvancedSkills/GridContainer,  # 修正网格名称
		$Control/Background/SkillContainer/MasterSkills/GridContainer     # 修正网格名称
	]
	
	for grid in grids:
		if grid:  # 确保网格存在
			for node in grid.get_children():
				if node.has_meta("skill_id"):
					var skill_id = node.get_meta("skill_id")
					update_node_state(node, skill_id)

func _on_learned_new_skill():
	print("检测到新技能学习，更新所有节点状态")
	update_all_nodes()
	draw_connections()

# 显示技能信息
func _on_skill_info_requested(skill_id):
	if not skill_data.has(skill_id):
		push_error("错误：无效的技能ID - " + str(skill_id))
		return
	
	var skill = skill_data[skill_id]
	
	# 更新技能标题
	if $Control/Background/DescriptionPanel/SkillTitle:
		$Control/Background/DescriptionPanel/SkillTitle.text = skill.name
	
	# 构建描述文本
	var description = ""
	if skill.has("description"):
		description += skill.description + "\n\n"
	
	description += "所需等级: " + str(skill.cost)
	
	# 检查技能是否已学习
	var learned = false
	var can_afford = false
	var player_level = 0
	
	if is_instance_valid(stats):
		# 如果stats是对象
		if stats is Object:
			if stats.has_method("has_skill"):
				learned = stats.has_skill(skill_id)
			
			if stats.get("level") != null:
				player_level = stats.level
				can_afford = player_level >= skill.cost
		# 如果stats是字典
		elif typeof(stats) == TYPE_DICTIONARY:
			if stats.has("skills"):
				if typeof(stats.skills) == TYPE_ARRAY:
					learned = skill_id in stats.skills
				elif typeof(stats.skills) == TYPE_DICTIONARY:
					learned = stats.skills.has(skill_id)
				print("从字典中检查技能是否已学习: ", learned)
			
			if stats.has("level"):
				player_level = stats.level
				can_afford = player_level >= skill.cost
				print("从字典中获取玩家等级: ", player_level, ", 是否可以学习: ", can_afford)
		else:
			print("警告：stats类型未知，无法检查技能状态")
	else:
		print("警告：stats无效，无法检查技能状态")
	
	# 添加玩家当前等级信息
	description += "\n当前等级: " + str(player_level)
	
	# 添加技能状态信息
	if learned:
		description += "\n\n状态: 已学习"
	else:
		if can_afford:
			description += "\n\n状态: 可学习"
		else:
			description += "\n\n状态: 等级不足"
	
	# 添加技能依赖信息
	if skill.has("requires") and typeof(skill.requires) == TYPE_ARRAY and skill.requires.size() > 0:
		description += "\n\n前置技能: "
		for i in range(skill.requires.size()):
			var req_id = skill.requires[i]
			if skill_data.has(req_id):
				description += skill_data[req_id].name
				if i < skill.requires.size() - 1:
					description += ", "
	
	# 更新描述文本
	if $Control/Background/DescriptionPanel/SkillDescription:
		$Control/Background/DescriptionPanel/SkillDescription.text = description
	
	# 显示描述面板
	if $Control/Background/DescriptionPanel:
		$Control/Background/DescriptionPanel.visible = true
	
	print("显示技能信息：", skill.name)

func draw_connections():
	var connections_node = $Control/Background/SkillContainer/Connections
	if not is_instance_valid(connections_node):
		push_error("错误：Connections节点不存在！")
		return
	
	connections_node.clear_points()
	
	if not skill_data or not is_instance_valid(stats):
		push_error("错误：技能数据或玩家数据无效！")
		return
	
	for skill_id in skill_data:
		if skill_data[skill_id].has("requires"):
			var requires = skill_data[skill_id].requires
			if typeof(requires) == TYPE_ARRAY:
				for req_id in requires:
					if not skill_data.has(req_id):
						continue
					
					var source_node = find_skill_node(req_id)
					var target_node = find_skill_node(skill_id)
					
					if source_node and target_node:
						var source_rect = source_node.get_global_rect()
						var target_rect = target_node.get_global_rect()
						
						var source_center = source_rect.position + source_rect.size / 2
						var target_center = target_rect.position + target_rect.size / 2
						
						var source_learned = false
						var target_learned = false
						
						if stats is Object and stats.has_method("has_skill"):
							source_learned = stats.has_skill(req_id)
							target_learned = stats.has_skill(skill_id)
						elif typeof(stats) == TYPE_DICTIONARY and stats.has("skills"):
							if typeof(stats.skills) == TYPE_ARRAY:
								source_learned = req_id in stats.skills
								target_learned = skill_id in stats.skills
							else:
								source_learned = stats.skills.has(req_id)
								target_learned = stats.skills.has(skill_id)
						
						var color = Color(0.8, 0.3, 0.9, 0.8) if source_learned and target_learned else Color(0.5, 0.5, 0.5, 0.5)
						connections_node.default_color = color
						
						# 转换为局部坐标
						var local_source = connections_node.to_local(source_center)
						var local_target = connections_node.to_local(target_center)
						
						connections_node.add_point(local_source)
						connections_node.add_point(local_target)

	connections_node.visible = true
	connections_node.z_index = -1

func _process(delta):
	# 更新调试计时器
	debug_timer += delta
	
	# 每隔一段时间输出调试信息
	if debug_timer >= debug_interval:
		debug_timer = 0.0
		
		# 获取鼠标位置
		var mouse_pos = get_viewport().get_mouse_position()
		print("鼠标位置: ", mouse_pos)
		
		# 检查所有技能节点的学习按钮
		var grids = [
			$Control/Background/SkillContainer/BasicSkills/GridContainer,
			$Control/Background/SkillContainer/AdvancedSkills/GridContainer,
			$Control/Background/SkillContainer/MasterSkills/GridContainer
		]
		
		for grid in grids:
			if grid:  # 确保网格存在
				for node in grid.get_children():
					if node.has_meta("skill_id"):
						var skill_id = node.get_meta("skill_id")
						var learn_button = node.get_node_or_null("LearnButton")
						
						if learn_button:
							# 计算按钮的全局矩形
							var button_rect = Rect2(learn_button.global_position, learn_button.size)
							
							# 检查鼠标是否在按钮上
							if button_rect.has_point(mouse_pos):
								var button_text = learn_button.get_node_or_null("Text")
								print("鼠标悬停在技能 ", skill_data[skill_id].name, " 的学习按钮上")
								print("按钮状态: 文本=", button_text.text if button_text else "无文本", ", 禁用=", learn_button.disabled)
								print("按钮全局位置: ", learn_button.global_position)
								print("按钮大小: ", learn_button.size)
								print("按钮矩形: ", button_rect)
								
								# 检查按钮是否可以接收鼠标事件
								print("按钮鼠标过滤模式: ", learn_button.mouse_filter)
								print("按钮焦点模式: ", learn_button.focus_mode)
								print("按钮Z索引: ", learn_button.z_index)
								
								# 检查按钮的父节点
								print("按钮父节点: ", learn_button.get_parent().name)
								print("按钮在父节点中的索引: ", learn_button.get_index())

# 添加鼠标输入处理函数
func _input(event):
	if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		print("检测到鼠标左键点击，位置: ", event.position)
		
		# 检查是否点击了学习按钮
		var grids = [
			$Control/Background/SkillContainer/BasicSkills/GridContainer,
			$Control/Background/SkillContainer/AdvancedSkills/GridContainer,  # 修正网格名称
			$Control/Background/SkillContainer/MasterSkills/GridContainer     # 修正网格名称
		]
		
		for grid in grids:
			if grid:  # 确保网格存在
				for node in grid.get_children():
					if node.has_meta("skill_id"):
						var skill_id = node.get_meta("skill_id")
						var learn_button = node.get_node_or_null("LearnButton")
						
						if learn_button:
							# 计算按钮的全局矩形
							var button_rect = Rect2(learn_button.global_position, learn_button.size)
							
							# 检查鼠标是否点击了按钮
							if button_rect.has_point(event.position):
								print("检测到点击学习按钮: ", skill_data[skill_id].name)
								print("手动调用_on_skill_selected函数")
								_on_skill_selected(skill_id)
								return

func _gui_input(event):
	if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		print("技能树接收到鼠标点击事件，位置: ", event.position)
		
		# 将全局位置转换为局部位置
		var local_pos = event.position - $Control/Background/SkillContainer.position
		
		# 检查是否点击了学习按钮
		var grids = [
			$Control/Background/SkillContainer/BasicSkills/GridContainer,
			$Control/Background/SkillContainer/AdvancedSkills/GridContainer,
			$Control/Background/SkillContainer/MasterSkills/GridContainer
		]
		
		for grid in grids:
			if grid:  # 确保网格存在
				for node in grid.get_children():
					if node.has_meta("skill_id"):
						var skill_id = node.get_meta("skill_id")
						var learn_button = node.get_node_or_null("LearnButton")
						
						if learn_button:
							# 计算按钮的全局矩形
							var button_rect = Rect2(
								node.position + learn_button.position, 
								learn_button.size
							)
							
							# 检查鼠标是否点击了按钮
							if button_rect.has_point(local_pos):
								print("检测到点击学习按钮: ", skill_data[skill_id].name)
								print("手动调用_on_skill_selected函数")
								_on_skill_selected(skill_id)
								get_viewport().set_input_as_handled()  # 标记事件已处理
								return
		
		# 无论是否点击到按钮，都消费掉左键点击事件
		get_viewport().set_input_as_handled()  # 标记事件已处理
		
		# 如果点击的不是技能描述面板区域，则隐藏描述面板
		if $Control/Background/DescriptionPanel:
			var desc_panel = $Control/Background/DescriptionPanel
			var panel_rect = desc_panel.get_global_rect()
			if not panel_rect.has_point(event.position) and desc_panel.visible:
				desc_panel.visible = false
